#include "sessionmanager.h"
namespace apollo
{
	namespace core
	{
		SessionManager::SessionManager(QObject *parent)
			: QObject(parent)
		{

		}

		SessionManager::~SessionManager()
		{

		}
		void SessionManager::init(QSharedPointer<SystemConfig> &config)
		{
			systemConfig = config;
		}

		void SessionManager::send(QString& commandName, MessagePtr msg)
		{
		}
		MessagePtr SessionManager::request(QString& commandName, MessagePtr request)
		{
			return MessagePtr(NULL);
		}
		MessagePtr SessionManager::login(MessagePtr request)
		{
			loginRequest = request;
			return MessagePtr(NULL);
		}

		QSharedPointer<Session> SessionManager::getSession(QString &connectionName, bool createNotExisted )
		{
			if(sessions.contains(connectionName))
			{
				return sessions.value(connectionName);
			}
			if(createNotExisted)
			{
				return QSharedPointer<Session>(NULL);
			}

			if(loginRequest.isNull())
			{
				THROW_EXP("loginRequest is NULL, cannot create session with remote.") ;
			}
			QSharedPointer<ConnectionConfig> config = systemConfig->getConnectionConfig(connectionName);
			if(!config)
			{
				THROW_EXP(connectionName +  "'s connection config can not be defined.") ;
			}
			QSharedPointer<Session> session(new Session(config));
			MessagePtr resp = session->connect(loginRequest);
			if(session->getState().state == SessionState::Login)
			{
				if(config->isPrimary)
				{
					loginResponse = resp;
				}
				sessions[connectionName] = session;
				return session;
			}
			else
			{
				return QSharedPointer<Session>(NULL);
			}

		}

	}}
